﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZK.Common;
using ZK.InterfaceServer;
using ZK.HardWareBLL;
using FastReport;
using System.Diagnostics;

namespace ZK.YHP_TransManage.UC
{
    /// <summary>
    /// 门卫室打印榜单
    /// </summary>
    public partial class PrintPoundList : Form
    {
        private string errorStr = string.Empty;
        /// <summary>
        /// 一页显示多少个数据
        /// </summary>
        int OnePageShowList = 14;
        /// <summary>
        /// 页数
        /// </summary>
        int count = 1;
        /// <summary>
        /// 室外读卡器
        /// </summary>
        //private MW_102N_CardReader mW_102N_CardReader;
        /// <summary>
        /// 运销车辆信息
        /// </summary>
        private Models.GetTruckYxInfoRceiveM yxYsTransportReturnDto;

        private WFAutoSizeHelper wFAutoSizeHelper = new WFAutoSizeHelper();

        Models.ScalesPrint scalesPrint = new Models.ScalesPrint();
        PrintPreviewDialog printPriview = new PrintPreviewDialog();
        List<Models.GetWeightBillsRceiveM1> getWeightBillsRceiveM1s;
        //private string nowCardNum = "";
        public PrintPoundList()
        {
            InitializeComponent();
            yxYsTransportReturnDto = new Models.GetTruckYxInfoRceiveM();

            // Common.DelegateHelper.MW_102N_MessageReceivedEvent += MW_102N_MessageReceived;

            //window change event
            wFAutoSizeHelper.GetAllInitInfo(this.Controls[0], this);
            this.StartPosition = FormStartPosition.CenterScreen;
            //Common.DelegateHelper.SendWidthHeightEvent += SendWidthHeight;

            aspnetPager1.OnPageChanged += AspnetPager1_OnPageChanged;

            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter;
            dataGridView1.AutoGenerateColumns = true;
        }

        private void AspnetPager1_OnPageChanged(object sender, EventArgs e)
        {
            ShowData(out count);
        }

        private void ShowData(out int count, bool res = true)
        {
            // Stopwatch stopwatch = new Stopwatch();
            // stopwatch.Start();
            int nums;
            dataGridView1.DataSource = null;
            string txtCurrentPage = aspnetPager1.Controls["panel1"].Controls["txtCurrentPage"].Text.Trim();
            if (string.IsNullOrWhiteSpace(txtCurrentPage)) txtCurrentPage = "1";
            nums = Convert.ToInt32(txtCurrentPage);

            Models.GetWeightBillsRceiveM getWeightBillsRceiveM = new Models.GetWeightBillsRceiveM();

            Models.GetWeightBillsSendM getWeightBillsSendM = new Models.GetWeightBillsSendM()
            {
                currentPage = nums,
                pageSize = this.OnePageShowList,
                cardNo = textBoxCardNum.Text.Trim(),
                truckNo = textBoxCarNum.Text.Trim(),
                shipperName = "杨伙盘"
            };
            // var s1 = stopwatch.ElapsedMilliseconds;
            getWeightBillsRceiveM = AutoControlTransportApiServer.GetWeightBills(getWeightBillsSendM);
            // var s2 = stopwatch.ElapsedMilliseconds;
            // Common.Log4.LogManage.WriteDebug("磅单列表时间：" + (s2 - s1));
            if (getWeightBillsRceiveM != null && getWeightBillsRceiveM.data.Count > 0)
            {
                getWeightBillsRceiveM1s = getWeightBillsRceiveM.data;
                List<Models.PrintViewM> printViewMs = getWeightBillsRceiveM.data.Select(p => new Models.PrintViewM()
                {
                    cardNo = p.cardNo,
                    truckNo = p.truckNo,
                    sendType = p.sendType,
                    yxState = p.yxState,
                    driver = p.driver,
                    BillState = p.billState,
                    MZTime = p.mz == null ? "" : p.mzTime.Substring(5)


                }).ToList();
                dataGridView1.DataSource = printViewMs;
                count = getWeightBillsRceiveM.total;
            }
            else
            {
                count = 0;
            }

            ShowPage(count, res);

        }
        /// <summary>
        /// 提示信息的最大长度
        /// </summary>
        private int InfoMaxLength = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InfoMaxLength"));
        /// <summary>
        /// 在显示在页面中的提示信息的长度超过的个数，截取的比例
        /// </summary>
        private int InfoMaxLengthCut = Convert.ToInt32(Common.AppConfigHelper.GetAppSettings("InfoMaxLengthCut"));

        /// <summary>
        /// 页面上显示信息
        /// </summary>
        /// <param name="str"></param>
        private void PageShow(string str)
        {

            this.Invoke(new Action(() =>
            {
                // textBoxInfo.tex
                int leg = textBoxInfo.TextLength;
                string infoTest = textBoxInfo.Text;
                if (leg > InfoMaxLength)
                {
                    infoTest = infoTest.Substring(leg / InfoMaxLengthCut);
                    textBoxInfo.Text = infoTest;
                }
                textBoxInfo.AppendText("--" + str + "\n");
            }));
            // }

        }
        /// <summary>
        /// 分页控件
        /// </summary>
        /// <param name="list"></param>
        private void ShowPage(int num, bool res = true)
        {
            aspnetPager1.PageSize = OnePageShowList;//设置显示记录数
            if (res)
                aspnetPager1.DrawControl(num);
            else
                aspnetPager1.DrawControlFirst(num);

        }




        /// <summary>
        /// 窗口变化委托事件
        /// </summary>
        /// <param name="Width"></param>
        /// <param name="height"></param>
        private void SendWidthHeight(int Width, int height)
        {
            if (wFAutoSizeHelper.ControlsInfo.Count > 0)//如果字典中有数据，即窗体改变
            {
                wFAutoSizeHelper.ControlsChangeInit(Width, height);//表示pannel控件
                wFAutoSizeHelper.ControlsChange(this.Controls[0]);
            }
        }




        /// <summary>
        /// 判断是否打印预览，并关闭打印页面。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Document_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            System.Drawing.Printing.PrintDocument printDocument = sender as System.Drawing.Printing.PrintDocument;
            bool printRes = printDocument.PrintController.IsPreview;
            if (!printRes)
            {
                printPriview.Close();
            }
        }

        /// <summary>
        /// 获取当前选定的行数据
        /// </summary>
        /// <returns></returns>
        private Models.GetWeightBillsRceiveM1 GetWeightBillsRceiveM1()
        {
            var nowRow = dataGridView1.CurrentRow;
            string cardNum = nowRow.Cells[3].Value.ToString();
            Models.GetWeightBillsRceiveM1 getWeightBillsRceiveM1 = getWeightBillsRceiveM1s.Where(p => p.cardNo == cardNum).FirstOrDefault();
            return getWeightBillsRceiveM1;
        }
        /// <summary>
        /// 境内+磅单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                PageShow("境内票打印");
                Models.GetWeightBillsRceiveM1 resM = GetWeightBillsRceiveM1();
                PrintCMTN(resM);
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteErr(ex.ToString());
                PageShow(ex.Message);
            }


        }
        /// <summary>
        /// 境外+ 磅单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                PageShow("境外票打印");
                Models.GetWeightBillsRceiveM1 resM = GetWeightBillsRceiveM1();
                PrintCMTW(resM);
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteErr(ex.ToString());
                PageShow(ex.Message);
            }
        }

        /// <summary>
        /// 上站票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                PageShow("上站打印");
                Models.GetWeightBillsRceiveM1 resM = GetWeightBillsRceiveM1();
                PrintSZT(resM);
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteErr(ex.ToString());
                PageShow(ex.Message);
            }
        }
        /// <summary>
        /// 煤管票 境内
        /// </summary>
        private void PrintCMTN(Models.GetWeightBillsRceiveM1 m)
        {
            var resM = AutoControlTransportApiServer.AddInnerWeightBill(m.wbid);
            if (!resM.success)
            {
                PageShow(resM.msg + " 请联系管理员");
            }
        }

        /// <summary>
        /// 煤管票 境外
        /// </summary>
        private void PrintCMTW(Models.GetWeightBillsRceiveM1 m)
        {
            Models.CMTM.CpSendMM sendm = new Models.CMTM.CpSendMM()
            {
                mScaleNum = 1,
                mCard = m.cardNo,
                mCNumber = m.truckNo,
                mTare = Convert.ToSingle(m.pz)
            };
            var cpRes = CMTServer.SendCP(sendm);

            if (cpRes.errorMsg != "OK")
            {
                PageShow("境外票皮重上传失败!");
                return;
            }
            Models.CMTM.WCXSSendM sendm2 = new Models.CMTM.WCXSSendM()
            {
                mCname = m.driver,
                mSort = m.coalName,
                mTarget = m.uploadPlace,
                mCtype = m.truckTypeName,
                mType = m.coalName,
                uuid = cpRes.uuid,
                mPrice = Convert.ToSingle(m.salePrice),
                mNt = Convert.ToSingle(m.jz),
                mGr = Convert.ToSingle(m.mz),
                mCNumber = m.truckNo
            };

            var resMWCXS = CMTServer.SendWCXS(sendm2);
            if (resMWCXS.errorMsg != "OK")
            {
                PageShow("境外票完成销售上传失败！");
                return;
            }

            PageShow("境外票上传成功！");
            //bool res = CMTServer.SendOld(new Models.CMTM.OldM()
            //{
            //    mCname = m.driver,
            //    mCNumber = m.truckNo,
            //    SN = "1",
            //    mSort = m.coalName,
            //    mCtype = m.truckTypeName,
            //    mGr = Convert.ToSingle(m.mz),
            //    mTare = Convert.ToSingle(m.pz),
            //    mTarget = "陕西",
            //    mType = m.coalName
            //});
            //if (!res)
            //{
            //    PageShow("境外票通讯错误！");
            //}
        }
        /// <summary>
        /// 上站票
        /// </summary>
        private void PrintSZT(Models.GetWeightBillsRceiveM1 m)
        {
            var res = ZK.InterfaceServer.USMServer.SendMessage(new Models.DeliveryInfo()
            {
                coalYard = m.shipperName,
                code = m.wbCode,
                consigneeOrgName = m.receivingPartyName,
                consigneeStationName = m.shortName,
                createUserName = "",
                driverName = m.driver,
                goodsCategoryName = m.coalName,
                grossTime = m.mzTime,
                grossWeight = m.mz,
                initialTest = "",
                invoiceRoom = "",
                isNormalVehicle = "0",
                loadTime = m.loadingTime,
                netWeight = m.jz,
                overWeight = "",
                tareTime = m.pzTime,
                tareWeight = m.pz,
                vehicleNo = m.truckNo
            });
            PageShow(res.msg);
            if (res.result == "fail") PageShow("操作失败，请重试");

        }

        private void PrintPound(Models.GetWeightBillsRceiveM1 getWeightBillsRceiveM1)
        {
            if (getWeightBillsRceiveM1 != null)
            {
                Report report = new Report();
                List<Models.PoundPrintM> poundPrintMs = new List<Models.PoundPrintM>();
                decimal price = (Convert.ToDecimal(getWeightBillsRceiveM1.jz) * Convert.ToDecimal(getWeightBillsRceiveM1.salePrice));
                string priceUpper = Number_String.ConvertToChinese(price);
                Models.PoundPrintM poundPrintM = new Models.PoundPrintM()
                {
                    Title = AppConfigHelper.GetAppSettings("PoundTitle"),
                    CustomerSign = "",
                    Drawer = Common.IConfig.GetSetuserInfo.LoginAccount,
                    BuyCoalCompanyName = getWeightBillsRceiveM1.receivingPartyName,
                    CarNumber = getWeightBillsRceiveM1.truckNo,
                    DriverName = getWeightBillsRceiveM1.driver,
                    CoalMax = getWeightBillsRceiveM1.coalName,
                    CoalMin = getWeightBillsRceiveM1.coalName,
                    FootText = "FootText",
                    MoneyMax = priceUpper,
                    MoneyMin = price.ToString("f2"),
                    NetWeight = getWeightBillsRceiveM1.jz,
                    RoughWeight = getWeightBillsRceiveM1.mz,
                    Payee = "",
                    PaymentMethod = Enum.GetName(typeof(Common.SysDefinitionEnum.PayType), getWeightBillsRceiveM1.payType),
                    Price = getWeightBillsRceiveM1.salePrice,
                    RoughWeightTime = getWeightBillsRceiveM1.mzTime,
                    TareWeight = getWeightBillsRceiveM1.pz,
                    TicketNumber = getWeightBillsRceiveM1.wbCode,
                };
                poundPrintMs.Add(poundPrintM);
                report.Load(@"BoundPrint.frx");
                report.RegisterData(poundPrintMs, "m");
                //预览打印
                //report.Show();
                //report.Dispose();

                //静默打印
                report.PrintSettings.ShowDialog = false;//选择打印机页面是否显示
                report.PrintSettings.Printer = AppConfigHelper.GetAppSettings("printName");
                report.Print();
                report.Dispose();

                var printWeightBillRes = AutoControlTransportApiServer.PrintWeightBill(getWeightBillsRceiveM1.wbid);
                if (!printWeightBillRes.success)
                {
                    Common.Log4.LogManage.WriteErr(printWeightBillRes.msg);
                    PageShow(printWeightBillRes.msg);
                }
            }


        }

        private void PrintPoundList_SizeChanged(object sender, EventArgs e)
        {
            if (wFAutoSizeHelper.ControlsInfo.Count > 0)//如果字典中有数据，即窗体改变
            {
                wFAutoSizeHelper.ControlsChangeInit(this.Controls[0]);//表示pannel控件
                wFAutoSizeHelper.ControlsChange(this.Controls[0]);
                // Common.DelegateHelper.SendWidthHeightEvent?.Invoke(this.Controls[0].Width, this.Controls[0].Height);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            PageShow("正在查询");
            aspnetPager1.Controls["panel1"].Controls["txtCurrentPage"].Text = "1";
            count = 1;
            ShowData(out count, false);
            // aspnetPager1.Controls["panel1"].Controls["txtCurrentPage"].Text = "1";
        }
        /// <summary>
        /// 磅单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                PageShow("打印磅单");
                Models.GetWeightBillsRceiveM1 resM = GetWeightBillsRceiveM1();
                PrintPound(resM);
                button1_Click(null, null);
            }
            catch (Exception ex)
            {

                Common.Log4.LogManage.WriteErr(ex.ToString());
                PageShow(ex.Message);
            }
        }
    }


}
